package com.gdit.zax.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gdit.zax.Constant;
import com.gdit.zax.dao.DynamicDao;
import com.gdit.zax.dao.UserDao;
import com.gdit.zax.entitys.Dynamic;
import com.gdit.zax.factory.DAOFactory;
import com.gdit.zax.utils.DBUtil;
import com.gdit.zax.utils.O;
import com.gdit.zax.utils.TextUtil;
import com.gdit.zax.utils.VeriFicUtil;

/**
 * 动态json接口
 * @author lenovo
 *
 */
public class JDynamic extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String accesstoken = request.getParameter("accesstoken");
		int type = TextUtil.String2int(request.getParameter("type"), -1);
		int page = TextUtil.String2int(request.getParameter("page"), 1);
		
		//检测参数
		if (TextUtil.isEmpty(accesstoken)) {
			O.printFail(response, 1, "请检查accesstoken参数!");
			return;
		}
		if (type < 0) {
			O.printFail(response, 1, "请检查type参数!");
			return;
		}
		
		
		int uid = VeriFicUtil.getVFID(accesstoken);
		Connection conn = DBUtil.getConnection();
		
		if (uid == Integer.MIN_VALUE || uid == Integer.MAX_VALUE) {
			O.printNoLogin(response);
			return;
		}
		
		if (conn==null) {
			O.printFail(response, 1000, "数据库连接失败!");
			return;
		}
		
		
		DAOFactory dao  = DAOFactory.init(conn, request, response);
		DynamicDao ddao = dao.getDynamicDao();
		ArrayList<Dynamic> list = null;
		if (type==Constant.DYNAMIC_type_all) {
			list = ddao.getMyAllDynamic(uid, page, 10);
		} else if (type==Constant.DYNAMIC_type_system) {
			list = ddao.getMySystemDynamic(uid, page, 10);
		} else if (type==Constant.DYNAMIC_type_seerecode) {
			list = ddao.getMySeeDynamic(uid, page, 10);
		} else if (type==Constant.DYNAMIC_type_downrecode)  {
			list = ddao.getMyDownDynamic(uid, page, 10);
		} else if (type==Constant.DYNAMIC_type_comme)  {
			O.printSuccess(response,ddao.getMyCommDynamic(uid, page, 10));
		} else {
			O.printFail(response, 1, "请检测type参数!");
		}
		
		if (list!=null) {
			ArrayList<Dynamic> list2 = new ArrayList<Dynamic>();
			for (int i = 0; i < list.size(); i++) {
				Dynamic dym = list.get(i);
				dym.setPic(Constant.WEBRoot + dym.getPic());
				list2.add(dym);
			}
			O.printSuccess(response, list2);
		}
	}

}
